import BasePlugin from './BasePlugin';

/**
 * 图层插件 - 处理画布图层管理
 */
export default class LayerPlugin extends BasePlugin {
    constructor() {
        super();
        this.layers = [];
        this.activeLayer = null;
        this.layerCounter = 0;
    }

    /**
     * 初始化插件
     */
    init(editor) {
        super.init(editor);
        this._setupEventListeners();
        this._initializeLayers();
    }

    /**
     * 初始化图层列表
     */
    _initializeLayers() {
        if (!this.canvas) return;

        // 清空现有图层
        this.layers = [];
        this.layerCounter = 0;

        // 为画布上的每个对象创建图层
        this.canvas.getObjects().forEach(obj => {
            this._createLayer(obj);
        });

        this._emitLayerEvent('initialize', this.layers);
    }

    /**
     * 创建新图层
     */
    _createLayer(obj) {
        const layer = {
            id: `layer_${++this.layerCounter}`,
            name: obj.name || `图层 ${this.layerCounter}`,
            object: obj,
            visible: true,
            locked: false,
            opacity: obj.opacity || 1
        };

        this.layers.push(layer);
        return layer;
    }

    /**
     * 添加图层
     */
    addLayer(obj, options = {}) {
        if (!this.isEnabled() || !this.canvas || !obj) return;

        const layer = this._createLayer(obj);

        // 应用选项
        if (options.name) layer.name = options.name;
        if (options.visible !== undefined) this.setLayerVisibility(layer.id, options.visible);
        if (options.locked !== undefined) this.setLayerLock(layer.id, options.locked);
        if (options.opacity !== undefined) this.setLayerOpacity(layer.id, options.opacity);

        this.canvas.add(obj);
        this._emitLayerEvent('add', layer);
        return layer;
    }

    /**
     * 删除图层
     */
    removeLayer(layerId) {
        if (!this.isEnabled() || !layerId) return;

        const layerIndex = this.layers.findIndex(layer => layer.id === layerId);
        if (layerIndex === -1) return;

        const layer = this.layers[layerIndex];
        this.canvas.remove(layer.object);
        this.layers.splice(layerIndex, 1);

        if (this.activeLayer && this.activeLayer.id === layerId) {
            this.activeLayer = null;
        }

        this._emitLayerEvent('remove', layer);
    }

    /**
     * 获取所有图层
     */
    getLayers() {
        return [...this.layers];
    }

    /**
     * 获取图层信息
     */
    getLayer(layerId) {
        return this.layers.find(layer => layer.id === layerId);
    }

    /**
     * 设置图层名称
     */
    setLayerName(layerId, name) {
        const layer = this.getLayer(layerId);
        if (!layer) return;

        layer.name = name;
        this._emitLayerEvent('rename', layer);
    }

    /**
     * 设置图层可见性
     */
    setLayerVisibility(layerId, visible) {
        const layer = this.getLayer(layerId);
        if (!layer) return;

        layer.visible = visible;
        layer.object.visible = visible;
        this.canvas.renderAll();
        this._emitLayerEvent('visibility', layer);
    }

    /**
     * 设置图层锁定状态
     */
    setLayerLock(layerId, locked) {
        const layer = this.getLayer(layerId);
        if (!layer) return;

        layer.locked = locked;
        layer.object.selectable = !locked;
        layer.object.evented = !locked;
        this._emitLayerEvent('lock', layer);
    }

    /**
     * 设置图层透明度
     */
    setLayerOpacity(layerId, opacity) {
        const layer = this.getLayer(layerId);
        if (!layer) return;

        layer.opacity = opacity;
        layer.object.opacity = opacity;
        this.canvas.renderAll();
        this._emitLayerEvent('opacity', layer);
    }

    /**
     * 移动图层位置
     */
    moveLayer(layerId, direction) {
        const layer = this.getLayer(layerId);
        if (!layer) return;

        const currentIndex = this.layers.indexOf(layer);
        let newIndex;

        if (direction === 'up') {
            if (currentIndex < this.layers.length - 1) {
                newIndex = currentIndex + 1;
                layer.object.moveTo(newIndex);
            }
        } else if (direction === 'down') {
            if (currentIndex > 0) {
                newIndex = currentIndex - 1;
                layer.object.moveTo(newIndex);
            }
        } else if (direction === 'top') {
            newIndex = this.layers.length - 1;
            layer.object.moveTo(newIndex);
        } else if (direction === 'bottom') {
            newIndex = 0;
            layer.object.moveTo(newIndex);
        }

        if (newIndex !== undefined) {
            // 更新图层数组
            this.layers.splice(currentIndex, 1);
            this.layers.splice(newIndex, 0, layer);
            this._emitLayerEvent('move', layer);
        }
    }

    /**
     * 复制图层
     */
    duplicateLayer(layerId) {
        const layer = this.getLayer(layerId);
        if (!layer) return;

        layer.object.clone((clonedObj) => {
            // 稍微偏移克隆对象的位置
            clonedObj.set({
                left: clonedObj.left + 10,
                top: clonedObj.top + 10
            });

            const newLayer = this.addLayer(clonedObj, {
                name: `${layer.name} 副本`
            });

            this._emitLayerEvent('duplicate', newLayer);
        });
    }

    /**
     * 合并图层
     */
    mergeLayers(layerIds) {
        if (!this.isEnabled() || !layerIds || layerIds.length < 2) return;

        const layers = layerIds.map(id => this.getLayer(id)).filter(Boolean);
        if (layers.length < 2) return;

        // 创建临时画布
        const tempCanvas = document.createElement('canvas');
        const tempCtx = tempCanvas.getContext('2d');

        // 设置临时画布尺寸为画布尺寸
        tempCanvas.width = this.canvas.width;
        tempCanvas.height = this.canvas.height;

        // 按顺序绘制图层
        layers.forEach(layer => {
            if (layer.visible) {
                layer.object.render(tempCtx);
            }
        });

        // 创建新的图片对象
        fabric.Image.fromURL(tempCanvas.toDataURL(), (mergedImage) => {
            // 删除原图层
            layers.forEach(layer => {
                this.removeLayer(layer.id);
            });

            // 添加合并后的新图层
            const newLayer = this.addLayer(mergedImage, {
                name: '合并图层'
            });

            this._emitLayerEvent('merge', newLayer);
        });
    }

    /**
     * 发送图层事件
     */
    _emitLayerEvent(type, data) {
        this.editor.emit('layer:' + type, {
            type,
            data
        });
    }

    /**
     * 设置事件监听
     */
    _setupEventListeners() {
        if (!this.canvas) return;

        // 监听对象添加事件
        this.canvas.on('object:added', (e) => {
            if (!this.isEnabled()) return;

            const obj = e.target;
            // 检查是否已经存在对应的图层
            const existingLayer = this.layers.find(layer => layer.object === obj);
            if (!existingLayer) {
                this._createLayer(obj);
            }
        });

        // 监听对象移除事件
        this.canvas.on('object:removed', (e) => {
            if (!this.isEnabled()) return;

            const obj = e.target;
            const layerIndex = this.layers.findIndex(layer => layer.object === obj);
            if (layerIndex !== -1) {
                this.layers.splice(layerIndex, 1);
            }
        });

        // 监听选择事件
        this.canvas.on('selection:created', (e) => {
            if (!this.isEnabled()) return;

            const obj = e.target;
            const layer = this.layers.find(layer => layer.object === obj);
            if (layer) {
                this.activeLayer = layer;
                this._emitLayerEvent('select', layer);
            }
        });

        this.canvas.on('selection:cleared', () => {
            if (!this.isEnabled()) return;

            if (this.activeLayer) {
                const previousLayer = this.activeLayer;
                this.activeLayer = null;
                this._emitLayerEvent('deselect', previousLayer);
            }
        });
    }

    /**
     * 销毁插件
     */
    destroy() {
        if (this.canvas) {
            this.layers = [];
            this.activeLayer = null;
            this.layerCounter = 0;
        }
        super.destroy();
    }
} 